package com.bookshop.promotion.logic;

import java.io.Serializable;

import com.bookshop.dataOperator.TXTHelper;
import com.bookshop.vo.PromotionConfigVO;


public class PromotionConfig implements Serializable{
	private static final long serialVersionUID = -3205635819143184982L;
	private static final String CONFIG_FILE_NAME = "promotionConfig";
	
	private static PromotionConfig promotionConfig;
	double mDiscountRate;
	double mEqualValue;
	int mEqualMaxuseCount;
	
	ICreditExchangeStrategy mRule;
	
	private PromotionConfig() {
		mRule = new CreditExchangeStrategy(1);
	}
	
	public int getMaxUseCount(){
		return mEqualMaxuseCount;
	}
	
	public double getEqualValue(){
		return mEqualValue;
	}
	
	public double getDiscountRate(){
		return mDiscountRate;
	}
	
	public static PromotionConfig instance(){
		if (promotionConfig == null) {
			promotionConfig = (PromotionConfig) TXTHelper.deSerialization(CONFIG_FILE_NAME);
		} 
		return promotionConfig;
	}
	
	public void reset(double pDiscountRate,double pEqualValue,int pEqualMaxuseCount,double pRate){
		reset(pDiscountRate, pEqualValue, pEqualMaxuseCount, new CreditExchangeStrategy(pRate));
	}
	
	public void reset(double pDiscountRate, double pEqualValue, int pEqualMaxuseCount,ICreditExchangeStrategy pCreditExchangeStrategy) {
		mDiscountRate = pDiscountRate;
		mEqualValue = pEqualValue;
		mEqualMaxuseCount = pEqualMaxuseCount;
		mRule = pCreditExchangeStrategy;
		updateFile();
	}
	
	public double exchangeCredit(double pExpense){
		return mRule.exchangeCredit(pExpense);
	}

	public void setExchangeRule(ICreditExchangeStrategy pRule){
		mRule = pRule;
	}
	
	public PromotionConfigVO getConfigVO(){
		PromotionConfigVO vo = new PromotionConfigVO();
		vo.update(mDiscountRate, mEqualValue, mEqualMaxuseCount, mRule);
		return vo;
	}
	
	private void updateFile(){
		TXTHelper.serialization(this, CONFIG_FILE_NAME);
	}
	
	@Override
	public String toString(){
		return mDiscountRate + " " + mEqualValue + " " + mEqualMaxuseCount + " " + ((CreditExchangeStrategy)mRule).mRate;
	}
	
//	public static void main(String[] args){
//		PromotionConfig promotionConfig = new PromotionConfig();
//		promotionConfig.reset(0.8, 50, 2, new CreditExchangeStrategy(1));
//		TXTHelper.serialization(promotionConfig, CONFIG_FILE_NAME);
//	}
}
